package gui.beans;

import validators.Validator;
import actions.Action;

public class Step {

	public final static String[] STEPSTATUS = { "Iniciar", "Finalizar", "Marcar erronea" };

	public final static int NOSTARTED = 0;
	public final static int STARTED = 1;
	public final static int ERROR = 2;
	public final static int COMPLETED = 3;

	private String name = null;
	private Step[] substeps = null;
	private Step next = null;
	private Step parent = null;
	private int status = NOSTARTED;

	private String errorMsg = null;
	
	private Action action = null;
	private Validator validator = null;

	public Step(String name, Step[] substeps, Step next, Action action, Validator validator) {
		this.name = name;
		this.substeps = substeps;
		if (substeps != null)
			for (int i = 0; i < substeps.length; i++)
				substeps[i].parent = this;
		this.next = next;

		this.action = action;
		this.validator = validator;
	}

	public String getName() {
		return name;
	}

	public Step[] getSubsteps() {
		return substeps;
	}

	public int substepsSize() {
		if (substeps == null)
			return 0;
		return substeps.length;
	}

	public boolean hasSubsteps() {
		if ((substeps == null) || (substeps.length == 0))
			return false;
		return true;
	}

	public Step getParent() {
		return parent;
	}

	public void setParent(Step parent) {
		this.parent = parent;
	}

	public int getStatus() {
		return status;
	}

	public void changeStatus(String statusName) {
		changeStatus(resolveStatus(statusName));
	}

	public void changeStatus(int status) {
		if (status < 0 || status > 3)
			return;

		this.status = status;

		if (action != null)
			action.fire(this);

		if (validator != null)
			validator.validate(this);

		if ((status == 3) && (next != null) && (next.getStatus() == 0))
			next.changeStatus(1);

		if ((status == 3) && (next == null) && (parent != null)) {
			parent.changeStatus(3);
		}

		if ((status == 1) && (substeps != null) && (substeps[0].getStatus() == 0))
			substeps[0].changeStatus(1);
	}
	
	public String getErrorMsg() {
		return errorMsg;
	}

	public void setErrorMsg(String errorMsg) {
		this.errorMsg = errorMsg;
	}

	@Override
	public String toString() {
		return name;
	}

	private int resolveStatus(String statusName) {
		if (statusName.equals("Iniciar"))
			return STARTED;
		if (statusName.equals("Finalizar"))
			return COMPLETED;
		if (statusName.equals("Marcar erronea"))
			return ERROR;
		return -1;
	}
}
